package cars

import (
	"beegoProject18/models/auth"
	"beegoProject18/utils"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"math"
	"time"
)

type CarsApplyController struct {
	beego.Controller
}

func (c *CarsApplyController) Get() {

	o := orm.NewOrm()

	// 先通过cars查询出车辆
	qs := o.QueryTable("sys_cars")
	carsData := []auth.Cars{}

	// 每页显示数据-4条 (pagePerNum)
	pagePerNum := 5

	var count int64 = 0

	// 当前页 (currentPage)
	currentPage, err := c.GetInt("page")
	// err 当点击页面时候没有获取到当前页也就是null，所以默认显示第一页
	if err != nil {
		currentPage = 1
	}

	/*
		增加查询：
	*/
	offsetNum := pagePerNum * (currentPage - 1)

	kw := c.GetString("kw")

	/* 查询日志 */
	ret := fmt.Sprintf("当前页:%d,查询条件:%s", currentPage, kw)
	logs.Info(ret)

	if kw != "" {
		count, _ = qs.Filter("is_delete", 0).Filter("name__contains", kw).Count()
		// 关联查询   .RelatedSel()
		qs.Filter("is_delete", 0).Filter("name__contains", kw).Limit(pagePerNum).Offset(offsetNum).RelatedSel().All(&carsData)
	} else {
		// 总数据量
		count, _ = qs.Filter("is_delete", 0).Count()
		// 用户详细信息查询
		qs.Filter("is_delete", 0).Limit(pagePerNum).Offset(offsetNum).RelatedSel().All(&carsData)
	}

	// 总页数 (count) =  总数据量 / 每页数据量   注：需要转换成int类型
	countPage := int(math.Ceil(float64(count) / float64(pagePerNum)))

	// 判断上一页
	prePage := 1
	if currentPage == 1 {
		prePage = currentPage
	} else if currentPage > 1 {
		// 上一页
		prePage = currentPage - 1
	}

	// 下一页
	nextPage := 1
	// 如果当前页小于总页数
	if currentPage < countPage {
		// 下一页 就等于 当前页+1
		nextPage = currentPage + 1
		// 如果当前页面大于等于总页数
	} else if currentPage >= countPage {
		// 下一页 就等于 当前页
		nextPage = currentPage
	}

	// 引用倒入到函数page.go
	pageMap := utils.Paginator(currentPage, pagePerNum, count)

	c.Data["page_map"] = pageMap
	c.Data["cars_data"] = carsData
	c.Data["prePage"] = prePage         /* 上一页*/
	c.Data["nextPage"] = nextPage       /* 下一页 */
	c.Data["currentPage"] = currentPage /* 当前页 */
	c.Data["countPage"] = countPage     /* 总页数 */
	c.Data["count"] = count
	c.Data["kw"] = kw

	c.TplName = "cars/cars-apply-list.html"
}

func (c *CarsApplyController) ToApply() {
	id, _ := c.GetInt("id")
	c.Data["id"] = id
	c.TplName = "cars/cars-apply.html"
}

func (c *CarsApplyController) DoApply() {
	reason := c.GetString("reason")
	destination := c.GetString("destination")
	returnDate := c.GetString("return_date")
	returnNewDate, _ := time.Parse("2006-01-02", returnDate) // 将string类型转换成时间类型
	carsId, _ := c.GetInt("cars_id")
	uid := c.GetSession("id")

	user := auth.User{Id: uid.(int)} // 将 interface 类型转换成 int 类型
	carsDate := auth.Cars{Id: carsId}

	o := orm.NewOrm()

	// 默认: ReturnStatus=0; AuditStatus=3; IsActive=1
	carsApply := auth.CarsApply{
		User:         &user,
		Cars:         &carsDate,
		Reason:       reason,
		Destination:  destination,
		ReturnDate:   returnNewDate,
		ReturnStatus: 0,
		AuditStatus:  3,
		IsActive:     1,
	}

	// 增加申请之后不可重新申请逻辑,更新 sys_cars表内状态值
	o.QueryTable("sys_cars").Filter("id", carsId).Update(orm.Params{
		"status": 2,
	})

	messageMap := map[string]interface{}{}
	_, err := o.Insert(&carsApply)
	if err != nil {
		messageMap["code"] = 10001
		messageMap["msg"] = "申请失败"
	} else {
		messageMap["code"] = 200
		messageMap["msg"] = "申请成功"
	}
	c.Data["json"] = messageMap
	c.ServeJSON()

}

func (c *CarsApplyController) MyApply() {

	o := orm.NewOrm()
	qs := o.QueryTable("sys_cars_apply")
	carApply := []auth.CarsApply{}

	pagePerNum := 5
	var count int64 = 0

	currentPage, err := c.GetInt("page")
	if err != nil {
		currentPage = 1
	}

	offsetNum := pagePerNum * (currentPage - 1)

	kw := c.GetString("kw")

	// 通过session获取到当前的用户id
	userId := c.GetSession("id")

	ret := fmt.Sprintf("当前页:%d,查询条件:%s", currentPage, kw)
	logs.Info(ret)

	if kw != "" {
		// 关联查询 从表关系(Cars) 通过（表名sys_cars） 查询（字段名称name）| 增加过滤只查询自己的数据不能查询别人的 userId并转换成int类型
		count, _ = qs.Filter("is_delete", 0).Filter("Cars__name__contains", kw).Filter("user_id", userId.(int)).Count()
		// 关联查询 从表关系(Cars) 通过（表名sys_cars） 查询（字段名称contains）
		qs.Filter("is_delete", 0).Filter("Cars__name__contains", kw).Limit(pagePerNum).Offset(offsetNum).RelatedSel().Filter("user_id", userId.(int)).All(&carApply)
	} else {
		count, _ = qs.Filter("is_delete", 0).Filter("user_id", userId.(int)).Count()
		qs.Filter("is_delete", 0).Limit(pagePerNum).Offset(offsetNum).RelatedSel().Filter("user_id", userId.(int)).All(&carApply)
	}

	countPage := int(math.Ceil(float64(count) / float64(pagePerNum)))

	prePage := 1
	if currentPage == 1 {
		prePage = currentPage
	} else if currentPage > 1 {
		prePage = currentPage - 1
	}

	nextPage := 1
	if currentPage < countPage {
		nextPage = currentPage + 1
	} else if currentPage >= countPage {
		nextPage = currentPage
	}

	pageMap := utils.Paginator(currentPage, pagePerNum, count)

	c.Data["page_map"] = pageMap
	c.Data["cars_apply"] = carApply
	c.Data["prePage"] = prePage
	c.Data["nextPage"] = nextPage
	c.Data["currentPage"] = currentPage
	c.Data["countPage"] = countPage
	c.Data["count"] = count
	c.Data["kw"] = kw

	c.TplName = "cars/my-apply-list.html"
}

func (c *CarsApplyController) AuditApply() {

	o := orm.NewOrm()
	qs := o.QueryTable("sys_cars_apply")
	carApply := []auth.CarsApply{}

	pagePerNum := 5
	var count int64 = 0

	currentPage, err := c.GetInt("page")
	if err != nil {
		currentPage = 1
	}

	offsetNum := pagePerNum * (currentPage - 1)

	kw := c.GetString("kw")

	/*// 通过session获取到当前的用户id   无需查询地理用户，查询所有即可
	userId := c.GetSession("id")*/

	ret := fmt.Sprintf("当前页:%d,查询条件:%s", currentPage, kw)
	logs.Info(ret)

	if kw != "" {
		// 注意反向查询
		count, _ = qs.Filter("is_delete", 0).Filter("Cars__name__contains", kw).Count()
		// 关联查询 从表关系(Cars) 通过（表名sys_cars） 查询（字段名称contains）
		qs.Filter("is_delete", 0).Filter("Cars__name__contains", kw).Limit(pagePerNum).Offset(offsetNum).RelatedSel().All(&carApply)
	} else {
		count, _ = qs.Filter("is_delete", 0).Count()
		qs.Filter("is_delete", 0).Limit(pagePerNum).Offset(offsetNum).RelatedSel().All(&carApply)
	}

	countPage := int(math.Ceil(float64(count) / float64(pagePerNum)))

	prePage := 1
	if currentPage == 1 {
		prePage = currentPage
	} else if currentPage > 1 {
		prePage = currentPage - 1
	}

	nextPage := 1
	if currentPage < countPage {
		nextPage = currentPage + 1
	} else if currentPage >= countPage {
		nextPage = currentPage
	}

	pageMap := utils.Paginator(currentPage, pagePerNum, count)

	c.Data["page_map"] = pageMap
	c.Data["cars_apply"] = carApply
	c.Data["prePage"] = prePage
	c.Data["nextPage"] = nextPage
	c.Data["currentPage"] = currentPage
	c.Data["countPage"] = countPage
	c.Data["count"] = count
	c.Data["kw"] = kw
	c.TplName = "cars/audit-apply-list.html"
}

func (c *CarsApplyController) ToAuditApply() {
	/*获取传过来的ID*/
	id, _ := c.GetInt("id")
	o := orm.NewOrm()
	qs := o.QueryTable("sys_cars_apply")

	// 查询数据储存
	carsApply := auth.CarsApply{}

	qs.Filter("id", id).One(&carsApply)

	c.Data["cars_apply"] = carsApply
	c.TplName = "cars/audit-apply.html"

}

func (c *CarsApplyController) DoAuditApply() {
	fmt.Printf("DoAuditApply")
	option := c.GetString("option")
	auditStatus, _ := c.GetInt("audit_status")
	id, _ := c.GetInt("id") /*获取审核的ID*/

	o := orm.NewOrm()
	qs := o.QueryTable("sys_cars_apply")
	/*更新数据*/
	_, err := qs.Filter("id", id).Update(orm.Params{
		"audit_option": option,
		"audit_status": auditStatus,
	})

	// 页面返回
	messageMap := map[string]interface{}{}

	if err != nil {
		messageMap["code"] = 10001
		messageMap["msg"] = "申请失败"
	}
	messageMap["code"] = 200
	messageMap["msg"] = "申请成功"

	c.Data["json"] = messageMap
	c.ServeJSON()
}

func (c *CarsApplyController) DoReturn() {
	id, _ := c.GetInt("id")
	o := orm.NewOrm()
	qs := o.QueryTable("sys_cars_apply")
	/*将归还状态改为1*/
	qs.Filter("id", id).Update(orm.Params{
		"return_status": 1,
	})

	/*将车辆状态修改为可借*/
	carsApply := auth.CarsApply{}
	qs.Filter("id", id).One(&carsApply)
	o.QueryTable("sys_cars").Filter("id", carsApply.Cars.Id).Update(orm.Params{
		"status": 1,
	})
	c.Redirect(beego.URLFor("CarsApplyController.MyApply"), 302)
}
